<?php
/**
 *MY_model model 文件
 *@author Cuil <lntschampion@163.com>
 *@date 2016-02-14
 */
class MY_model extends CI_Model {
    protected $pk = array("id");
	public $db;
    public $type;
    protected $slave;
    protected $master;
	function __construct(){
		
		parent::__construct();
		$this->conn();
	}
	
	//初始化
	function conn($params = array()){
		$type = '' ;
		$type =(isset($params['dbname']) && $params['dbname'] )? $params['dbname'] : 'default' ;
		
		$this->db = $this->slave = $this->master = $this->load->database($type,true);
	}

	/**
	 * ----------------------------------------------------
	 * 获取数据列表 
	 * ----------------------------------------------------
	 * @param $field(string)(array) 查询字段
	 * @param $where (array) 查询数组
	 * @param $limit(int) 查询条数
	 * @param $offset(int) 开始位置
	 * @param $order(string) 排序
	 * @auther Cuil <lntschampion@163.com>
	 * @version 2015-02-14
	 */
	public function getList( $field = '*' , $where = array() , $limit = 1 , $offset = Null , $order = '' , $group = '')
	{
		$this->slave->from( $this->table );
		$this->slave->select( $field );
		$this->like( $where );
		$this->_in( $where );
		$this->_or( $where );
		$this->slave->where( $where );
		if(intval( $limit ) > 0){
			$this->slave->limit( $limit , $offset);
		}
	
		if( !empty( $order))
		{
			$this->slave->order_by( $order);
		}
		if( !empty( $group ))
		{
			$this->slave->group_by( $group );
		}
		$rec = $this->slave->get();
		//echo $this->slave->last_query();
		return $rec->result_array();
	}

	/**
	 * ----------------------------------------------------------------
	 * 多表关联查多条数据
	 * ----------------------------------------------------------------
	 * @param $tables (array) array('goods' => 'goods' ,'库名'	=> '别名');
	 * @param $join (array) array('goods.goods_id = detail.goods_id');
	 * @param $field (array) 查询字符串 goods.id
	 * @param $where (array) 查询条件  array('goods.goods_id' => 1)
	 * @param $limit (int) 查询条数
	 * @param $offset (int) 偏移量
	 * @param $order (string)排序
	 * @return (array) 二维数组
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function getJoinList( $tables , $join , $field = "*" , $where , $limit = 1 , $offset = 0 , $order = NULL ,  $group = NULL)
	{
		$this->slave->select($field);
		$i = 0;
		foreach( $tables as $k => $v){
			if( $i == 0){
				$this->slave->from( $k." As ".$v);
			}else{
				$this->slave->join( $k." As ".$v , $join[$i-1] , 'left');
			}
			$i++;
		}
		$this->like( $where );
		$this->_in( $where );
		$this->_or( $where );
		$this->slave->where($where );
		$this->slave->limit($limit , $offset);
		if(isset($order)){
			$this->slave->order_by($order);
		}
		if( !empty( $group ))
		{
			$this->slave->group_by( $group );
		}
		$query = $this->slave->get();
		//echo $this->slave->last_query();
		return $query->result_array();
	}
	
	/**
	 *
	 * 模糊搜索	
	 * @param $where (array) 模糊搜索条件  array('or_where' => array('username' => $data['key']),);
	 * @modify		
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function like( &$where )
	{
		if( isset($where['search']) && !empty($where['search']) && is_array($where['search']))
		{
			foreach( $where['search'] as $k => $v)
			{
				foreach( $v as $key => $val)
				{
					$k = trim( $k );
					$this->slave->$k($key , $val);
				}
			}
			unset( $where['search']);
		}
	}
	
	/**
	 * IN搜索
	 * @param $where (array) 模糊搜索条件  $where['in'] = array('userid' => $ids);
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function _in( &$where ){
		if(isset($where['in']) && !empty($where['in']) && is_array($where['in'])){
			foreach ($where['in'] as $k => $v){
				$this->slave->where_in($k, $v);
			}
			unset($where['in']);
		}
	}
	
	/**
	 * OR搜索
	 * @param $where (array) 模糊搜索条件 $where['or'] = array('userid' => '1', 'username' => 'c');
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function _or( &$where ){
		if(isset($where['or']) && !empty($where['or']) && is_array($where['or'])){
			foreach ($where['or'] as $k => $v){
				if(is_array($v)){
					foreach($v as $ork => $orv){
						$this->slave->or_where($k, $orv);
					}
				}else{
					$this->slave->or_where($k, $v);
				}
			}
			unset($where['or']);
		}
	}
	
	
	/**
	 * --------------------------------------------------
	 * 获取一条数据
	 * ---------------------------------------------------
	 * @param $field(string)(array) 查询字段
	 * @param $where (array) 查询数组
	 * @param $order(string) 排序描述			
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function getRow(  $field = '*' , $where = array() , $order = '',$distinct=false )
	{
		$this->slave->from( $this->table );
		$this->slave->select( $field );
		if($distinct){
			$this->slave->distinct();
		}

		$this->like( $where );
		$this->_in( $where );
		$this->_or( $where );
		$this->slave->where( $where );
		$this->slave->limit( 1 );
		if( !empty( $order))
		{
			$this->slave->order_by( $order);
		}
		$rec = $this->slave->get();
		//echo $this->slave->last_query();
		return $rec->row_array();
	}
	
	/**
	 * --------------------------------------------------
	 * 获取一条数据
	 * ---------------------------------------------------
	 * @param $field(string)(array) 查询字段
	 * @param $where (array) 查询数组
	 * @param $order(string) 排序描述
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function getOne(  $field = '*' , $where = array() , $order = '',$distinct=false )
	{
	 $result = $this->getRow( $field , $where , $order,$distinct);
		
		if( !empty($result))
		{
			foreach($result as $k => $v  )
			{
				return $v;
			}
		}
		
		return '';
	}
	
	/**
	 * --------------------------------------------------
	 * 获取一条数据
	 * ---------------------------------------------------
	 * @param $field(string)(array) 查询字段
	 * @param $where (array) 查询数组
	 * @param $order(string) 排序描述
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function getJoinOne( $tables , $join , $field = "*" , $where  , $order = NULL )
	{
		$result = $this->getJoinRow( $tables , $join , $field , $where , $order);

		foreach($result as $k => $v  )
		{
			return $v;
		}
		return '';
	}
	
	/**
	 *----------------------------------------------------------------
	 * 多表关联查询一条数据
	 * ---------------------------------------------------------------
	 * @param $tables (array) array('goods' => 'goods' ,'库名'	=> '别名');
	 * @param $join (array) array('goods.goods_id = detail.goods_id');
	 * @param $field (array) 查询字符串 goods.id
	 * @param $where (array) 查询条件  array('goods.goods_id' => 1)
	 * @param $order (string)排序
	 * @return (array) 一维数组
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function getJoinRow( $tables , $join , $field = "*" , $where  , $order = NULL )
	{
		$this->slave->select($field);
		$i = 0;
		foreach( $tables as $k => $v){
			if( $i == 0){
				$this->slave->from( $k." As ".$v);
			}else{
				$this->slave->join( $k." As ".$v , $join[$i-1] , 'left');
			}
			$i++;
		}
		$this->like( $where );
		$this->_in( $where );
		$this->_or( $where );
		$this->slave->where($where );
		$this->slave->limit( 1 );
		if(isset($order)){
			$this->slave->order_by($order);
		}
		$query = $this->slave->get();
		//echo $this->slave->last_query();
		return $query->row_array();
	}
	/**
	 * 修改某一字段值-递增递减 
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function setFile( $data , $where )
	{
		$this->master->where( $where );
		foreach ($data as $k => $v ){
			$this->master->set($k , $v, FALSE);	
		}
		return $this->master->update($this->table );
	}
	/**
	 *
	 * 插入数据
	 * @param $data (array) 添加的数据
	 * @param $new_id (Bool) 是否返回ID
	 * @return (bool)(int) 返回 Bool 或 插入 自增ID
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function insertData( $data , $new_id = FALSE )
	{
		$rec = $this->master->insert( $this->table , $data);
		//echo $this->master->last_query();exit;
		if( $rec && $new_id){
			return $this->master->insert_id();
		}
		return $rec;
	}

	/***
	 * @param $data
	 * @return mixed
	 * @author Cuil <lntschampion@163.com>
	 * @date 2016-02-14
	 */
	public function insert_batch( $data )
	{
		$result = $this->db->insert_batch($this->table, $data);
// 		echo $this->db->last_query();
		return $result;
	}

	/**
	 *
	 * 插入数据
	 * @param $data (array) 添加的数据
	 * @param $new_id (Bool) 是否返回ID
	 * @return (bool)(int) 返回 Bool 或 插入 自增ID
	 * @author Cuil <lntschampion@163.com>
	 * @date  2016-02-14
	 */
	public function insertDatatotable( $data , $new_id = FALSE ,$table='')
	{
	    $table = $table ? $table : $this->table;
	    $rec = $this->master->insert( $table , $data);
	    //echo $this->master->last_query();exit;
	    if( $rec && $new_id){
	        return $this->master->insert_id();
	    }
	    return $rec;
	}
	
	function saveData( $data )
	{
		if( empty( $data['id']))
		{
			$id = $this->insertData( $data , true);
		}
		else
		{
			$where = array(
				'id' => $data['id'], 
			);
			$id = $data['id'];
			unset($data['id']);
			$this->updateData($data, $where);
		}
		return $id;
	}
	
	/**
	 *----------------------------------------------------------
	 * 编辑数据库条目
	 * ---------------------------------------------------------
	 * @param $where (array) 条件
	 * @param $data (array) 更新数据			
	 * @return (bool)
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function updateData( $data ,$where  )
	{
		return $this->master->update( $this->table ,$data , $where );
	}
	
	/**
	 *---------------------------------------------
	 * 物理删除数据			
	 * -------------------------------------------
	 * @param $where 删除where条件
	 * @return bool
	 * @author		Cuil <lntschampion@163.com>
	 * @date		2016-02-14
	 */
	public function delData( $where )
	{
		$r =  $this->master->delete( $this->table , $where );
		//echo $this->master->last_query();
		return $r;
	}
	
	public function last_query( $table = 'slave')
	{
		$table = ( $table == 'slave')?'slave':'master';
		return $this->$table->last_query();
	}
	
	public function __destruct(){
		if(DBLOG){
			$query = $this->get_queries();
			foreach($query as $k => $sql){
				$sql = str_replace(array("\r","\n"), ' ', $sql);
				Logs::db($sql);
			}
		}
	}
	/**
	 * 得到所有查询语句
	 * @param book $dump 是否在页面直接打印
	 * @return array $queries
	 */
	public function get_queries($dump = false){
		$queries = array();
		if(!empty($this->slave->queries)){
			$queries = $this->slave->queries;
			if($dump){
				Dump($this->slave->queries);
			}
		}
		return $queries;
	}


/**
 * 警告：以下方法在新项目中不允许再次使用
 * BY Cuil 2016-02-15
 */
/////////////////////////////////////////////////////////////////////////////////////////
	//插入一条数据
	function insert_one($table,$data){
		
		$this->db->insert($table,$data) ;
		
		return array(
			'affect_num'=>$this->db->affected_rows() ,
			'insert_id'=>$this->db->insert_id(),
			'sql'=>$this->db->last_query()
		);
	}
	
	//查询1条数据，返回结果
	function query_one($sql){		
		return $this->db->query($sql)->row_array();
	}
	
	//查询list data
	function querylist($sql){
		
		$result =array();
		$query = $this->db->query($sql);
		if($query){
			foreach($query->result_array() as $row){
	    		$result[] = $row ;
	    	}		
		}
    	return $result ;
	}
	
	//执行sql语句
	function exec($sql){
		$result = $this->db->query($sql);
		return $result;
	}
	
	//查询返回的结果
	function query_count($sql){
		
		$query = $this->db->query($sql);
		$num_array = $query->result_array();
		$num = 0 ;
		if(isset($num_array[0]) && !empty($num_array[0])){
			foreach ($num_array[0] as $k=>$v){
				$num = $v ;
				break ;
			}
		}	
		return $num ;
	}
	
	//删除数据
	function del_data($sql){
		$query = $this->db->query($sql);
		return $this->db->affected_rows(); //返回影响的行数
	
	}
	
	//修改数据
	function update_data($sql){
		$query = $this->db->query($sql);
		return $this->db->affected_rows(); //返回影响的行数
	}
	
	//判断数据表是否存在
	function isexits($tablename){
		$sql = "SHOW TABLES LIKE '". $tablename."'";
		return $this->db->query($sql)->num_rows();
	}
		
	/**
	 * Active Record
	 * 
	 * 参考手册：
	 * http://codeigniter.org.cn/user_guide/database/active_record.html
	 * 
	 * 例子
	 * $this->M_common->query('admin_user',array('group_id'=>4),array('user_id','user_name'));
	 * 
	 * $where 查询条件
	 * $where['uname'] = $uname;
	 * $where['create_time >= '] = $begin;
	 * 
	 * $orderby 排序
	 * $this->db->order_by('title desc'); 
	 * $this->db->order_by('title desc, name asc'); 
	 * 
	 */
	
	//查询
	function query($table,$where=array(),$cols='*',$limit=0,$offset=0,$orderby='',$in_field='',$in_where=array()){
		
		if(empty($table)){
			exit('请注意参数格式');
		}
		
		$query = array();
		//查询列
		$this->db->select($cols);
		
		//排序列
		if(!empty($orderby)){
			$this->db->order_by($orderby);
		}
		if(!empty($in_field)){
			$this->db->where_in("{$in_field}", $in_where);
		}
		
		if(empty($where)){
			if($limit==0){
				$query = $this->db->get($table);
			}else{
				$query = $this->db->get($table, $limit, $offset);
			}
		}else{
			if($limit==0){
				$query = $this->db->get_where($table, $where);
			}else{
				$query = $this->db->get_where($table, $where, $limit, $offset);
			}
		}
		
// 		echo $this->db->last_query(); //查看执行sql
// 		die();
		
		$result =array();
		if($query){
			foreach($query->result_array() as $row){
				$result[] = $row ;
			}
		}
		unset($query);
		return $result ;
	}
	
	//查询数量
	function queryCount($table,$where=array(),$in_field='',$in_where=array()){
		
		if(empty($table)){
			exit('请注意参数格式');
		}
		
		if(!empty($in_field)){
			$this->db->where_in("{$in_field}", $in_where);
		}
		$this->db->where($where);
		$this->db->from($table);
		return $this->db->count_all_results();
	}
	
	//插入一条数据
	function insert($table,$data){
		
		if(empty($table) || empty($data)){
			exit('请注意参数格式');
		}
		
		$this->db->insert($table,$data) ;
		return array(
			'affect_num'=>$this->db->affected_rows() ,
			'insert_id'=>$this->db->insert_id()
		);
	}
	
	//删除数据
	function delete($table,$where){
		
		if(empty($table) || empty($where)){
			exit('请注意参数格式');
		}
		
		$result = $this->db->delete($table, $where);
		return $this->db->affected_rows(); //返回影响的行数
	}
	
	//修改数据
	function update($talbe,$data,$where){
		if(empty($talbe) || empty($data) || empty($where)){
			exit('请注意参数格式');
		}
		$this->db->update($talbe, $data, $where);
		//echo $this->db->last_query(); //查看执行sql
		return $this->db->affected_rows();	//返回影响的行数
	}

	//更新时间为unix时间戳
	function update_time($table,$where,$filed='update_time'){
		$sql = "UPDATE {$table} SET {$filed} = UNIX_TIMESTAMP() WHERE ".$where;
		return $this->exec($sql);
    }

        /**
         * 根据对象ID获取指定对象
         * @param int $id 对象ID
         * @return object 
         */
        function get($id)
        {
            $params = array_combine( $this->pk, array($id) );
            return $this->db->get_where( $this->table, $params, 1 )->row();
        }

        /**
        * 根据唯一字段获取指定对象
        * @param string $key 字段名
        * @param string $value 字段值
        * @return object 
        */
        function getByUK( $key, $value )
        {
            return $this->db->get_where( $this->table, array($key => $value), 1 )->row();
        }
        /**
        * 保存指定对象，若id为null则为创建。
        * 支持复合主键对象，除第一个参数外，所有参数按pk的顺序填入
        * @param array $data
        * @param int $id 要保存对象的ID
        * @return boolean 成功返回true(Insert返回ID)，否则返回false
        */

       public function save( $data, $id = null ){
        if( $id ){
            $args   = func_get_args();
            array_shift( $args );
            $paramsk = array_combine( $this->pk, $args );
            $ret    = $this->db->update( $this->table, $data, $paramsk );
        }else{
            $ret = $this->db->insert( $this->table, $data );
            if ( $ret )
                $ret = $this->db->insert_id();

            if ( $ret === 0 )
                $ret = true;
        }

        
        return $ret;


       }
}
